#include <string.h>
#include <iostream>
using std::cout;
using std::endl;

class Point{
public:
    Point(int x, int y)
    :_x(x)
    ,_y(y)
    {
        cout << "Point(int,int)" << endl;
    }
    //主动地将拷贝构造函数写出来
    //拷贝构造函数也是构造函数
    //所以也可以写初始化列表
    Point(const Point & rhs)
    :_x(rhs._x)
    ,_y(rhs._y)
    {
        cout << "Point(const Point &)" << endl;
    }

    ~Point(){
        cout << "~Point()" << endl;
    }

    void print(){
        cout << "(" << _x << "," << _y << ")" <<endl;
    }

private:
    int _x;
    int _y;
};

class Computer{
public:
    Computer(const char * brand, float price)
    :_brand(new char[strlen(brand) + 1]())
    ,_price(price)
    {
        strcpy(_brand ,brand);
    }
    //编译器生成的拷贝构造函数如下
#if 0
    Computer(const Computer & rhs)
    :_brand(rhs._brand)//  _brand = rhs._brand
    ,_price(rhs._price)
    {
        cout << "Computer(const Computer &)" << endl;
    }
#endif
    Computer(const Computer & rhs)
    :_brand(new char[strlen(rhs._brand) + 1]())
    ,_price(rhs._price)
    {
        strcpy(_brand, rhs._brand);
        cout << "Computer(const Computer &)" << endl;
    }

    ~Computer(){
        if(_brand){
            delete [] _brand;
            _brand = nullptr;
        }
    }

    void print(){
        cout << "_brand=" << _brand << ",_price=" << _price << endl;
    }


private:
    char * _brand;
    float _price;
};

void test(){
    Point pt(1, 2);
    pt.print();
    Point pt2 = pt;
    pt2.print();
}

//思考题：为什么会出现double free
//请把这段代码对应的内存图示画出来
void test2(){
    Computer c1("apple", 7600);
    c1.print();
    //下面这行代码会调用拷贝构造函数
    Computer c2 = c1;
    c2.print();
}

int main()
{
    test2();
    return 0;
}

